package com.xjf.security.service;

import com.xjf.security.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 登录用户的信息获取
 *
 * @author xjf
 * @date 2020/2/20 10:46
 */
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private IUserService iUserService;

    /**
     * 用户登录获取用户信息
     * @param s 登录用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser user = iUserService.findByUsername(s);
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("用户不存在");
        }

        // 把角色放入认证器里
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        List<String> roles = user.getRoles();
        roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));

        // 该 User 是 SpringSecurity 的
        return new User(user.getUsername(),user.getPassword(),authorities);
    }
}
